<template>
  <div class="user-profile-page">
    <el-container>
      <el-header class="page-header">
        <h2>个人信息管理</h2>
        <p>管理您的个人资料和账户设置</p>
      </el-header>
      
      <el-main>
        <el-row :gutter="24">
          <!-- 左侧：个人信息卡片 -->
          <el-col :span="8">
            <el-card class="profile-card" shadow="never">
              <div class="profile-header">
                <div class="avatar-section">
                  <el-avatar :size="80" :src="userInfo?.avatar">
                    {{ userInfo?.username?.charAt(0) }}
                  </el-avatar>
                  <el-button 
                    type="primary" 
                    size="small" 
                    @click="showAvatarDialog = true"
                    class="avatar-upload-btn"
                  >
                    更换头像
                  </el-button>
                </div>
                <div class="user-basic-info">
                  <h3>{{ userInfo?.username || '未设置' }}</h3>
                  <p class="user-role">{{ getRoleText(userInfo?.role) }}</p>
                  <p class="join-date">加入时间：{{ formatDate(userInfo?.created_at) }}</p>
                </div>
              </div>
              
              <div class="profile-stats" v-if="userStats">
                <el-row :gutter="16">
                  <el-col :span="8">
                    <div class="stat-item">
                      <div class="stat-number">{{ userStats.properties_count }}</div>
                      <div class="stat-label">发布房源</div>
                    </div>
                  </el-col>
                  <el-col :span="8">
                    <div class="stat-item">
                      <div class="stat-number">{{ userStats.appointments_count }}</div>
                      <div class="stat-label">预约看房</div>
                    </div>
                  </el-col>
                  <el-col :span="8">
                    <div class="stat-item">
                      <div class="stat-number">{{ userStats.reviews_count }}</div>
                      <div class="stat-label">评价数量</div>
                    </div>
                  </el-col>
                </el-row>
              </div>
            </el-card>
          </el-col>

          <!-- 右侧：详细信息表单 -->
          <el-col :span="16">
            <el-card class="form-card" shadow="never">
              <el-tabs v-model="activeTab" type="card">
                <!-- 基本信息 -->
                <el-tab-pane label="基本信息" name="basic">
                  <el-form 
                    :model="profileForm" 
                    :rules="profileRules" 
                    ref="profileFormRef"
                    label-width="100px"
                    class="profile-form"
                  >
                    <el-row :gutter="20">
                      <el-col :span="12">
                        <el-form-item label="用户名" prop="username">
                          <el-input v-model="profileForm.username" placeholder="请输入用户名" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="真实姓名" prop="real_name">
                          <el-input v-model="profileForm.real_name" placeholder="请输入真实姓名" />
                        </el-form-item>
                      </el-col>
                    </el-row>

                    <el-row :gutter="20">
                      <el-col :span="12">
                        <el-form-item label="邮箱" prop="email">
                          <el-input v-model="profileForm.email" placeholder="请输入邮箱" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="手机号" prop="phone">
                          <el-input v-model="profileForm.phone" placeholder="请输入手机号" />
                        </el-form-item>
                      </el-col>
                    </el-row>

                    <el-row :gutter="20">
                      <el-col :span="12">
                        <el-form-item label="性别" prop="gender">
                          <el-select v-model="profileForm.gender" placeholder="请选择性别" style="width: 100%">
                            <el-option label="男" value="male" />
                            <el-option label="女" value="female" />
                            <el-option label="其他" value="other" />
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="生日" prop="birthday">
                          <el-date-picker
                            v-model="profileForm.birthday"
                            type="date"
                            placeholder="请选择生日"
                            style="width: 100%"
                            format="YYYY-MM-DD"
                            value-format="YYYY-MM-DD"
                          />
                        </el-form-item>
                      </el-col>
                    </el-row>

                    <el-form-item label="地址" prop="address">
                      <el-input 
                        v-model="profileForm.address" 
                        type="textarea" 
                        placeholder="请输入详细地址"
                        :rows="3"
                      />
                    </el-form-item>

                    <el-form-item label="个人简介" prop="bio">
                      <el-input 
                        v-model="profileForm.bio" 
                        type="textarea" 
                        placeholder="请输入个人简介"
                        :rows="4"
                      />
                    </el-form-item>

                    <el-form-item>
                      <el-button type="primary" @click="updateProfile" :loading="profileLoading">
                        保存修改
                      </el-button>
                      <el-button @click="resetProfileForm">重置</el-button>
                    </el-form-item>
                  </el-form>
                </el-tab-pane>

                <!-- 密码修改 -->
                <el-tab-pane label="密码修改" name="password">
                  <el-form 
                    :model="passwordForm" 
                    :rules="passwordRules" 
                    ref="passwordFormRef"
                    label-width="100px"
                    class="password-form"
                  >
                    <el-form-item label="原密码" prop="oldPassword">
                      <el-input 
                        v-model="passwordForm.oldPassword" 
                        type="password" 
                        placeholder="请输入原密码"
                        show-password
                      />
                    </el-form-item>

                    <el-form-item label="新密码" prop="newPassword">
                      <el-input 
                        v-model="passwordForm.newPassword" 
                        type="password" 
                        placeholder="请输入新密码"
                        show-password
                      />
                    </el-form-item>

                    <el-form-item label="确认密码" prop="confirmPassword">
                      <el-input 
                        v-model="passwordForm.confirmPassword" 
                        type="password" 
                        placeholder="请再次输入新密码"
                        show-password
                      />
                    </el-form-item>

                    <el-form-item>
                      <el-button type="primary" @click="changePassword" :loading="passwordLoading">
                        修改密码
                      </el-button>
                      <el-button @click="resetPasswordForm">重置</el-button>
                    </el-form-item>
                  </el-form>
                </el-tab-pane>
              </el-tabs>
            </el-card>
          </el-col>
        </el-row>
      </el-main>
    </el-container>

    <!-- 头像上传对话框 -->
    <el-dialog v-model="showAvatarDialog" title="更换头像" width="400px">
      <div class="avatar-upload">
        <el-upload
          class="avatar-uploader"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
          :http-request="uploadAvatar"
        >
          <img v-if="avatarPreview" :src="avatarPreview" class="avatar-preview" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
        <div class="upload-tips">
          <p>支持 JPG、PNG 格式</p>
          <p>文件大小不超过 2MB</p>
        </div>
      </div>
      <template #footer>
        <el-button @click="showAvatarDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmAvatarUpload" :loading="avatarLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useAuthStore } from '@/store/auth'
import { userAPI } from '@/api/user'
import { ElMessage } from 'element-plus'

const authStore = useAuthStore()

const activeTab = ref('basic')
const profileLoading = ref(false)
const passwordLoading = ref(false)
const avatarLoading = ref(false)
const showAvatarDialog = ref(false)
const avatarPreview = ref('')

const userInfo = computed(() => authStore.user)
const userStats = ref(null)

const profileForm = reactive({
  username: '',
  email: '',
  phone: '',
  real_name: '',
  gender: '',
  birthday: '',
  address: '',
  bio: ''
})

const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const profileRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const getRoleText = (role) => {
  const roleMap = {
    user: '普通用户',
    admin: '管理员'
  }
  return roleMap[role] || '未知'
}

const formatDate = (date) => {
  if (!date) return '未知'
  return new Date(date).toLocaleDateString('zh-CN')
}

const loadUserInfo = () => {
  if (userInfo.value) {
    Object.assign(profileForm, {
      username: userInfo.value.username || '',
      email: userInfo.value.email || '',
      phone: userInfo.value.phone || '',
      real_name: userInfo.value.real_name || '',
      gender: userInfo.value.gender || '',
      birthday: userInfo.value.birthday || '',
      address: userInfo.value.address || '',
      bio: userInfo.value.bio || ''
    })
  }
}

const loadUserStats = async () => {
  try {
    const res = await userAPI.getUserStats()
    if (res?.success) {
      userStats.value = res.data
    }
  } catch (error) {
    console.error('获取用户统计失败:', error)
  }
}

const updateProfile = async () => {
  try {
    await profileFormRef.value.validate()
    profileLoading.value = true

    const res = await userAPI.updateProfile(profileForm)
    if (res?.success) {
      ElMessage.success('个人信息更新成功')
      // 更新store中的用户信息
      authStore.setUser(res.data)
    } else {
      ElMessage.error(res?.message || '更新失败')
    }
  } catch (error) {
    console.error('更新个人信息失败:', error)
    ElMessage.error('更新失败，请重试')
  } finally {
    profileLoading.value = false
  }
}

const changePassword = async () => {
  try {
    await passwordFormRef.value.validate()
    passwordLoading.value = true

    const res = await userAPI.changePassword({
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword
    })
    
    if (res?.success) {
      ElMessage.success('密码修改成功')
      resetPasswordForm()
    } else {
      ElMessage.error(res?.message || '密码修改失败')
    }
  } catch (error) {
    console.error('修改密码失败:', error)
    ElMessage.error('修改失败，请重试')
  } finally {
    passwordLoading.value = false
  }
}

const resetProfileForm = () => {
  loadUserInfo()
}

const resetPasswordForm = () => {
  Object.assign(passwordForm, {
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  })
  passwordFormRef.value?.resetFields()
}

const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }

  // 预览图片
  const reader = new FileReader()
  reader.onload = (e) => {
    avatarPreview.value = e.target.result
  }
  reader.readAsDataURL(file)

  return false // 阻止自动上传
}

const uploadAvatar = () => {
  // 这里可以实现真实的文件上传逻辑
  // 暂时使用预览图片作为头像
}

const confirmAvatarUpload = async () => {
  if (!avatarPreview.value) {
    ElMessage.warning('请选择头像图片')
    return
  }

  try {
    avatarLoading.value = true
    
    // 这里应该调用真实的上传API
    // 暂时直接使用预览图片
    const res = await userAPI.updateProfile({ avatar: avatarPreview.value })
    
    if (res?.success) {
      ElMessage.success('头像更新成功')
      authStore.setUser(res.data)
      showAvatarDialog.value = false
      avatarPreview.value = ''
    } else {
      ElMessage.error(res?.message || '头像更新失败')
    }
  } catch (error) {
    console.error('上传头像失败:', error)
    ElMessage.error('头像更新失败，请重试')
  } finally {
    avatarLoading.value = false
  }
}

onMounted(() => {
  loadUserInfo()
  loadUserStats()
})
</script>

<style scoped>
.user-profile-page {
  min-height: 100vh;
  background: #f6f8fb;
}

.page-header {
  background: #fff;
  border-bottom: 1px solid #e8e8e8;
  padding: 24px;
  text-align: center;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #333;
}

.page-header p {
  margin: 0;
  color: #666;
}

.profile-card {
  height: fit-content;
}

.profile-header {
  display: flex;
  gap: 16px;
  margin-bottom: 24px;
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
}

.avatar-upload-btn {
  font-size: 12px;
  padding: 4px 12px;
}

.user-basic-info h3 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 20px;
}

.user-role {
  margin: 0 0 4px 0;
  color: #666;
  font-size: 14px;
}

.join-date {
  margin: 0;
  color: #999;
  font-size: 12px;
}

.profile-stats {
  border-top: 1px solid #f0f0f0;
  padding-top: 16px;
}

.stat-item {
  text-align: center;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: #666;
}

.form-card {
  min-height: 500px;
}

.profile-form,
.password-form {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px 0;
}

.avatar-upload {
  text-align: center;
}

.avatar-uploader {
  display: inline-block;
  margin-bottom: 16px;
}

.avatar-uploader :deep(.el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s;
  width: 120px;
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.avatar-preview {
  width: 120px;
  height: 120px;
  object-fit: cover;
  border-radius: 6px;
}

.upload-tips {
  color: #999;
  font-size: 12px;
}

.upload-tips p {
  margin: 4px 0;
}
</style>
